import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.*;

public class FilesTest {


    public static void main(String[] args) throws IOException {

        Path path = Paths.get("D:\\nio");
        boolean isExits = Files.exists(path);

        System.out.println("is Exits=" + isExits);
        if (!isExits) {
            Path newPath = Files.createDirectory(path);
            System.out.println("new Path=" + newPath);
        }

        Path path1 = Paths.get("D:\\nio2\\test");
        boolean path1Exits = Files.exists(path1);

        if (!path1Exits) {
            Path newPath2 = Files.createDirectories(path1);
            System.out.println("new newPath2=" + newPath2);
        }

        Path path3 = Paths.get("D:\\nio\\test.txt");
        Path path4 = Paths.get("D:\\nio2\\test\\copy-test.txt");

        if (!Files.exists(path3)) {
            Files.createFile(path3);
        }
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.put("Hello world".getBytes());

        // 写模式变为读模式
        byteBuffer.flip();

        FileChannel channel = FileChannel.open(path3, StandardOpenOption.READ, StandardOpenOption.WRITE);
        channel.write(byteBuffer);
        channel.close();


        // copy
        // 如果目标文件存在，则抛出异常 FileAlreadyExistsException,加入参数，如果存在，则替换
        Files.copy(path3, path4, StandardCopyOption.REPLACE_EXISTING);


        // 这里文件夹不为空，则删不掉，先删除文件，然后再删除文件夹
        Files.delete(path3);
        Files.delete(path);
    }

}
